import React,{useEffect,useState} from 'react';
import {Card,List} from 'antd';
import {Scrollbars} from 'react-custom-scrollbars';
import LinkButton from '../../components/LinkButton';
import {ArrowLeftOutlined} from '@ant-design/icons';
import {useLocation,useNavigate} from 'react-router-dom';
import {reqCategory} from '../../api';
import {BASE_IMG_URL} from '../../utils/constants';
import './index.less'

const Item = List.Item;

/**
 *商品管理详情页
 */
function ProductDetail(){
  // navigate跳转路由
  const navigate = useNavigate();
  // 获取product数据，回显
  const location = useLocation();
  const {product} = location.state;
  // 获取一级分类名称
  const [cName1,setCName1] = useState("");
  // 获取二级分类名称
  const [cName2,setCName2] = useState("");

  useEffect(function(){
    // 得到当前商品的分类ID
    const {pCategoryId,categoryId} = product;
    // 一级分类下的商品
    if(pCategoryId === '0'){
      reqCategory(categoryId).then(function(response){
        setCName1(response.data.name);
      });
    // 二级分类下的商品
    }else{
      // 获取一级分类列表
      reqCategory(pCategoryId).then(function(response){
        setCName1(response.data.name);
      })
      // 获取二级分类
      reqCategory(categoryId).then(function(response){
        setCName2(response.data.name);
      });
    }
  },[]);

  const title = (
    <span>
      <LinkButton onClick={function(){
        navigate('/product');
      }}>
        <ArrowLeftOutlined />
      </LinkButton>
      <span>商品详情</span>
    </span>
  );

  // 读取携带过来的state数据
  const {name, desc, price, detail, imgs} = product;

  return (
    <Scrollbars>
      <Card title={title} className="product-detail">
        <List>
          <Item>
            <span className="left">商品名称:</span>
            <span>{name}</span>
          </Item>
          <Item>
            <span className="left">商品描述:</span>
            <span>{desc}</span>
          </Item>
          <Item>
            <span className="left">商品价格:</span>
            <span>{price}元</span>
          </Item>
          <Item>
            <span className="left">所属分类:</span>
            <span>{cName1} {cName2 ? ' --> '+cName2 : ''}</span>
          </Item>
          <Item>
            <span className="left">商品图片:</span>
            <span>
              {
                imgs.map(img => (
                  <img
                    key={img}
                    src={BASE_IMG_URL + img}
                    className="product-img"
                    alt="img"
                  />
                ))
              }
            </span>
          </Item>
          <Item>
            <span className="left">商品详情:</span>
            <span dangerouslySetInnerHTML={{__html: detail}}>
            </span>
          </Item>
        </List>
      </Card>
    </Scrollbars>
  );
}

export default ProductDetail;